package com.app.piemoment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.LayoutParams;
import android.widget.TextView;

import com.app.piemoment.api.ApiResult;
import com.app.piemoment.api.ApiReturnResultListener;
import com.app.piemoment.api.QAAPI;
import com.app.piemoment.callback.PopoButtoCallBack;
import com.app.piemoment.entity.Question;
import com.app.piemoment.util.Utils;
import com.app.piemoment.view.PopupButton;

public class PersonalQuestionActivity extends BaseActivity {
	private LinearLayout gallery;
	protected ArrayList<Question> list;
	private TextView description;
	private LinearLayout radioGroup;
	private int position = 0;
	private Button btn_pre;
	private Button btn_next;

	public PersonalQuestionActivity() {
		mainViewId = R.layout.qa_activity;

	}

	@Override
	protected void initMainView() {
		initTitle(R.drawable.btn_back_bg,"问题", R.drawable.right_bg,0);
		gallery = (LinearLayout) findViewById(R.id.qa_gallery);
		description = (TextView)findViewById(R.id.description);
		radioGroup = (LinearLayout)findViewById(R.id.radioGroup1);
		
		btn_pre = (Button)findViewById(R.id.btn_pre);
		btn_next = (Button)findViewById(R.id.btn_next);
	}

	@Override
	protected void registerMainViewEvent() {
		btn_next.setOnClickListener(this);
		btn_pre.setOnClickListener(this);
	}

	@Override
	protected void processMainView() {
		getRandomQA();
	}

	private void getRandomQA() {
		QAAPI api = new QAAPI(this);
		api.setReturnResultListener(new ApiReturnResultListener() {
			
			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(LOAD_PROGRESS);
				if (ApiResult.RESULT_OK == apiResult.getResultCode()) {
					JSONObject jsonEntity = apiResult.getJsonEntity();
					try {
						if (jsonEntity != null) {
							if (jsonEntity.has("status")) {
								String result = jsonEntity.getString("status");
								if (ApiResult.Success.equals(result)) {
									if (jsonEntity.has("data")) {
										JSONArray array = jsonEntity.getJSONArray("data");
										if (array != null && array.length() > 0) {
											if (list == null) {
												list = new ArrayList<Question>();
											}
											Question info = null;
											//{"type":"multiple_choice_one_answer","possible_answers":["完全不能接受。","确定会结婚之后才能接受。","可以接受。"],"title":"你能接受婚前同居吗？","code":"876131"}

											for (int i = 0; i < array.length(); i++) {
												JSONObject obj = (JSONObject) array.opt(i);
												info = new Question();
												info.parser(obj);
												list.add(info);
											}
										}

									}
								}
							}
							updateUI(0);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
			
			@Override
			public <T> void onReturnLoading(int requestCode) {
				showDialog(LOAD_PROGRESS);
				
			}
			
			@Override
			public <T> void onReturnFailResult(int requestCode, ApiResult<T> apiResult) {
				dismissDialog(LOAD_PROGRESS);
			}
		});
		api.getRandomQuestion(1, this);
		
	}
	
	private void updateUI(int position) {
		Log.e("position", "position is " + position);
		if (list != null && list.size() > 0&&position<list.size()&&position>=0) {
			Question subject = list.get(position);
			description.setText(subject.getTitle());
			if (subject.getAnswers() != null) {
				LinearLayout.LayoutParams groupLP = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
				groupLP.setMargins(Utils.dipToPixels(this, 5), Utils.dipToPixels(this, 5), Utils.dipToPixels(this, 5), Utils.dipToPixels(this, 5));
				radioGroup.removeAllViews();
				RadioGroup.LayoutParams radioLP = new RadioGroup.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
				radioLP.setMargins(Utils.dipToPixels(this, 5), Utils.dipToPixels(this, 5), Utils.dipToPixels(this, 5), Utils.dipToPixels(this, 5));
				RadioGroup group = new RadioGroup(this);
				for (int i = 0; i < subject.getAnswers().length; i++) {
					String[] answers = subject.getAnswers();
					RadioButton radio = new RadioButton(this);
					radio.setId(i);
					radio.setBackgroundResource(R.drawable.item_creamy_white_bg);
					radio.setTextColor(getResources().getColor(R.color.text_black));
					radio.setButtonDrawable(android.R.color.transparent);
					radio.setGravity(Gravity.CENTER);
					// radio.setText(answers[i].substring(2));
					radio.setText(answers[i]);
					group.addView(radio,radioLP);
				}
				radioGroup.addView(group,groupLP);
			}
		}
		//图片展示
		/*if (gallery != null) {
			gallery.removeAllViews();
			LinearLayout.LayoutParams imageLP = new LinearLayout.LayoutParams(
					Utils.getScreenWidth(this) / 4,
					Utils.getScreenWidth(this) / 4);
			imageLP.setMargins(0, 5, 0, 5);
			for (int i = 0; i < 4; i++) {
				ImageView image = new ImageView(this);
				image.setImageResource(R.drawable.b);
				gallery.addView(image, imageLP);
			}
		}*/
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_left:
			super.onBackPressed();
			break;
		case R.id.btn_right:
			PopupButton pop = new PopupButton(this, btn_right, new String[]{"问题","回答"}, new PopoButtoCallBack() {

				@Override
				public void getCurrentValue(String value) {
					if("回答".equals(value)) {
						Intent intent = new Intent(PersonalQuestionActivity.this,PersonalAnswerActivity.class);
						startActivity(intent);
					}else {
						
					}
				}
				
			});
			if (pop != null && pop.isShowing()) {
				pop.dismissPop();
			} else {
				pop.showPopWindow();
			}
			break;
		case R.id.btn_next:
			answerQuestion();
			if(position<list.size()-1) {
				position ++;//更新下一题
			}
			updateUI(position);
			break;
		case R.id.btn_pre:
			if(position>0) {
				position --;//更新下一题
			}
			updateUI(position);
			break;
		default:
			break;
		}
	}

	private void answerQuestion() {
		if (list != null && list.size() > 0&&position<list.size()&&position>=0) {
			Question subject = list.get(position);
			QAAPI api = new QAAPI(this);
			api.setReturnResultListener(new ApiReturnResultListener() {
				
				@Override
				public <T> void onReturnSucceedResult(int requestCode,
						ApiResult<T> apiResult) {
					// {"message":"Answer added successfully !","status":"success"}
					if (ApiResult.RESULT_OK == apiResult.getResultCode()) {
						JSONObject jsonEntity = apiResult.getJsonEntity();
						try {
							if (jsonEntity != null) {
								if (jsonEntity.has("status")) {
									String result = jsonEntity.getString("status");
									if (ApiResult.Success.equals(result)) {
										Log.e("message", jsonEntity.getString("message"));
									}
								}
							}
						}catch(Exception e) {
							e.printStackTrace();
						}
					}	
				}
				
				@Override
				public <T> void onReturnLoading(int requestCode) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public <T> void onReturnFailResult(int requestCode, ApiResult<T> apiResult) {
					// TODO Auto-generated method stub
					
				}
			});
			RadioGroup group = (RadioGroup) radioGroup.getChildAt(0);
			String answer = null;
			if(subject.getAnswers()!=null&&group.getCheckedRadioButtonId()>=0) {
				answer = subject.getAnswers()[group.getCheckedRadioButtonId()];
			}
			Log.e("add", "code is " + subject.getCode() + " answer is " + answer);
			api.addAnswer(1, this, subject.getCode(),answer);
		}
		
	}

}